package com.ups.singlearner;

import com.badlogic.gdx.audio.analysis.FFT;
import com.ups.singlearner.util.NoteUtil;

import android.media.AudioFormat;
import android.media.AudioRecord;


public class AudioDetection {

	public static int getFrequency(short audioData[]) {
		int frequency;

		int bufferSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO,
				AudioFormat.ENCODING_PCM_16BIT);

		//audioData = new short [bufferSize];
		int p;
		int numCrossing=0; //initialize your number of zero crossings to 0

		for (p=0;p<bufferSize/4;p+=4) {
			if (audioData[p]>0 && audioData[p+1]<=0) numCrossing++;
			if (audioData[p]<0 && audioData[p+1]>=0) numCrossing++;
			if (audioData[p+1]>0 && audioData[p+2]<=0) numCrossing++;
			if (audioData[p+1]<0 && audioData[p+2]>=0) numCrossing++;
			if (audioData[p+2]>0 && audioData[p+3]<=0) numCrossing++;
			if (audioData[p+2]<0 && audioData[p+3]>=0) numCrossing++;
			if (audioData[p+3]>0 && audioData[p+4]<=0) numCrossing++;
			if (audioData[p+3]<0 && audioData[p+4]>=0) numCrossing++;
		}

		for (p=(bufferSize/4)*4;p<bufferSize-1;p++) {
			if (audioData[p]>0 && audioData[p+1]<=0) numCrossing++;
			if (audioData[p]<0 && audioData[p+1]>=0) numCrossing++;
		}                                   

		frequency=(8000/bufferSize)*(numCrossing/2);

		return frequency;
	}

	public static int getFrequencyFFT(short audioData[]) {

		float[] array = new float[4096];
		
		for (int i = 0 ; i< 4096 ; i++) {
			array[i] = audioData[i];
		}

		FFT fft = new FFT(4096, 8000);


		fft.forward(array);
		
		// get higher frequency
		/*int max = 0;
		for (int i = 0 ; i < mag.length ; i++) {
			if (mag[i] > mag[max]) {
				max = i;
			}
		}*/
		
		float[] freq = new float[7];
		freq[0] = fft.calcAvg(NoteUtil.DO_VALUE-5, NoteUtil.DO_VALUE+5);
		freq[1] = fft.calcAvg(NoteUtil.RE_VALUE-5, NoteUtil.RE_VALUE+5);
		freq[2] = fft.calcAvg(NoteUtil.MI_VALUE-5, NoteUtil.MI_VALUE+5);
		freq[3] = fft.calcAvg(NoteUtil.FA_VALUE-5, NoteUtil.FA_VALUE+5);
		freq[4] = fft.calcAvg(NoteUtil.SOL_VALUE-5, NoteUtil.SOL_VALUE+5);
		freq[5] = fft.calcAvg(NoteUtil.LA_VALUE-5, NoteUtil.LA_VALUE+5);
		freq[6] = fft.calcAvg(NoteUtil.SI_VALUE-5, NoteUtil.SI_VALUE+5);
		
		int max = 0;
		for (int i = 0 ; i < 7 ; i++) {
			if (freq[i] > freq[max])
				max = i;
		}
		
		switch (max) {
		case 0:
			return (int) NoteUtil.DO_VALUE; 
		case 1:
			return (int) NoteUtil.RE_VALUE;
		case 2:
			return (int) NoteUtil.MI_VALUE;
		case 3:
			return (int) NoteUtil.FA_VALUE;
		case 4:
			return (int) NoteUtil.SOL_VALUE;
		case 5:
			return (int) NoteUtil.LA_VALUE;
		case 6:
			return (int) NoteUtil.SI_VALUE;
		}
		return 7;
	}

}
